package com.top.ruizhong.main.home

import android.graphics.Color
import android.view.ViewGroup
import android.widget.ImageView
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ConvertUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.material.appbar.AppBarLayout
import com.module.lemlin.base.BaseAbstractFragment
import com.module.lemlin.base.RecyclerViewHolder
import com.module.lemlin.base.loadRoundImage
import com.module.lemlin.custom.GridSpacingItemDecoration
import com.module.lemlin.custom.SpacingItemDecoration
import com.top.ruizhong.R
import com.top.ruizhong.entity.Category
import com.top.ruizhong.main.cate.CateGoodsActivity
import com.top.ruizhong.main.goods.GoodsDetailsActivity
import com.top.ruizhong.main.host.SearchActivity
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerAdapter
import com.youth.banner.indicator.RectangleIndicator
import kotlinx.android.synthetic.main.fragment_main_home.*
import kotlinx.android.synthetic.main.include_home_bar.*
import kotlinx.android.synthetic.main.include_home_heads.*

class MainHomeFragment : BaseAbstractFragment(), AppBarLayout.OnOffsetChangedListener {


    companion object {
        fun newInstance(): MainHomeFragment {
            return MainHomeFragment()
        }
    }

    override val layoutResId: Int
        get() = R.layout.fragment_main_home


    private val homeBannerAdapter =
        object : BannerAdapter<String, RecyclerViewHolder>(mutableListOf()) {
            override fun onCreateHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
                val imageView = ImageView(parent.context)
                imageView.layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
                imageView.setPadding(
                    ConvertUtils.dp2px(13f), 0,
                    ConvertUtils.dp2px(13f), 0
                )
                imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                return RecyclerViewHolder(imageView)
            }

            override fun onBindView(
                holder: RecyclerViewHolder,
                data: String,
                position: Int,
                size: Int
            ) {
                (holder.itemView as ImageView).loadRoundImage(data, radius = 15)
            }
        }

    private val homeCategoryAdapter =
        object : BaseQuickAdapter<Category, BaseViewHolder>(R.layout.item_category_icon) {
            override fun convert(holder: BaseViewHolder, item: Category) {
                holder.setText(R.id.tvCategoryTitle, item.title)
                holder.getView<ImageView>(R.id.ivCategoryIcon).setImageResource(item.icon)
            }
        }

    private val homeGoodsAdapter =
        object : BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_goods_home) {
            override fun convert(holder: BaseViewHolder, item: String) {

            }
        }


    override fun initView() {
        //为Toolbar添加状态栏高度
        BarUtils.addMarginTopEqualStatusBarHeight(toolbarHome)
        BarUtils.addMarginTopEqualStatusBarHeight(includeHomeBar)
        //为AppBar设置滑动监听
        appBarHome.addOnOffsetChangedListener(this)

        //为RecyclerView设内边距
        includeHomeHeads.setPadding(
            ConvertUtils.dp2px(0f), (ConvertUtils.dp2px(85f) + BarUtils.getStatusBarHeight()),
            ConvertUtils.dp2px(0f), ConvertUtils.dp2px(0f)
        )

        //初始轮播视图
        vpHomeBanner.apply {
            indicator = RectangleIndicator(context)
            setIntercept(false)
        }.setOrientation(Banner.HORIZONTAL).setUserInputEnabled(true)
            .adapter = homeBannerAdapter

        //初始化分类视图
        rvHomeICategory.apply {
            val decoration = SpacingItemDecoration(
                nSpan = 5, vGap = ConvertUtils.dp2px((17f)), hGap = ConvertUtils.dp2px((13f))
            )
            addItemDecoration(decoration)
        }.adapter = homeCategoryAdapter.apply {
            setOnItemClickListener { _, _, _ ->
                CateGoodsActivity.open(activity = requireActivity())
            }
        }

        //初始化物品视图
        rvHomeGoodsBody.apply {
            val decoration = GridSpacingItemDecoration(
                spanCount = 2, spacing = ConvertUtils.dp2px((13f))
            )
            addItemDecoration(decoration)
        }.adapter = homeGoodsAdapter.apply {
            setOnItemClickListener { _, _, _ ->
                GoodsDetailsActivity.open(activity = requireActivity())
            }
        }

        //搜索
        flHomeSearch.setOnClickListener {
            SearchActivity.open(requireActivity())
        }
    }

    override fun initData() {

        val banners: MutableList<String> = mutableListOf<String>(
            "http://txcsicarefzcn.oss-cn-hangzhou.aliyuncs.com/uploads/20200926/0fe30ef1363c79bb84dab9204d6d5eb5.jpg",
            "http://txcsicarefzcn.oss-cn-hangzhou.aliyuncs.com/uploads/20200926/bd4ef6c0f82855699079a9b9aa7231a7.jpg",
            "http://txcsicarefzcn.oss-cn-hangzhou.aliyuncs.com/uploads/20200926/72fc7e09fcd3d6d13fdab37822a1cf94.jpg",
            "http://txcsicarefzcn.oss-cn-hangzhou.aliyuncs.com/uploads/20200926/be0d0de9f5a6ee6c3bc3d24ba48401a8.jpg",
            "http://txcsicarefzcn.oss-cn-hangzhou.aliyuncs.com/uploads/20200926/54c3f17807ee6ab24c0d7f31a54a82af.jpg",
            "http://txcsicarefzcn.oss-cn-hangzhou.aliyuncs.com/uploads/20200926/5187340e397e8dc66ea8fd3cbd127260.jpg"
        )
        homeBannerAdapter.setDatas(banners)


        val category1: MutableList<Category> = mutableListOf(
            Category(R.mipmap.ic_test_6, "美食外卖"),
            Category(R.mipmap.ic_test_5, "乳品烘焙"),
            Category(R.mipmap.ic_test_7, "速食冻品"),
            Category(R.mipmap.ic_test_8, "蛋糕甜品"),
            Category(R.mipmap.ic_test_9, "蔬菜专区"),
            Category(R.mipmap.ic_test_10, "洗发沐浴"),
            Category(R.mipmap.ic_test_11, "生活用品"),
            Category(R.mipmap.ic_test_12, "水果生鲜"),
            Category(R.mipmap.ic_test_13, "酒水饮料"),
            Category(R.mipmap.ic_test_14, "米面粮油")
        )
        homeCategoryAdapter.setNewInstance(category1)

        val goods: MutableList<String> = mutableListOf(
            "限时抢购1", "限时抢购2", "限时抢购3", "限时抢购4", "限时抢购5",
            "限时抢购6", "限时抢购7", "限时抢购8", "限时抢购9", "限时抢购10"
        )
        homeGoodsAdapter.setNewInstance(goods)
    }

    override fun onResume() {
        super.onResume()
        vpHomeBanner.start()
    }

    override fun onPause() {
        super.onPause()
        vpHomeBanner.stop()
    }

    override fun onDestroy() {
        super.onDestroy()
//        vpHomeBanner.destroy()
    }


    public var alphaStatus: Int = 0

    //搜索布局展开时顶部距离
    private val searchMaxTopMargin: Float =
        ConvertUtils.dp2px(45f).toFloat()

    //搜索布局关闭时顶部距离
    private val searchMinTopMargin: Float =
        ConvertUtils.dp2px(4.5f).toFloat()

    //搜索布局展开时的宽度
    private val searchMaxWidth: Float =
        (com.blankj.utilcode.util.ScreenUtils.getScreenWidth() - ConvertUtils.dp2px(26f)).toFloat()

    //搜索布局关闭时的宽度
    private val searchMinWidth: Float =
        (com.blankj.utilcode.util.ScreenUtils.getScreenWidth() - ConvertUtils.dp2px(80f)).toFloat()
    private val alphaMaxHeight: Float =
        ConvertUtils.dp2px(10f).toFloat()

    override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
        val offset: Float = verticalOffset * -0.65f

        var searchNewTopMargin: Float = searchMaxTopMargin - (offset * 1.5f)
        var searchNewWidth: Float = searchMaxWidth - (offset * 2.15f)
        val alphaNewHeight: Float = alphaMaxHeight - (offset * 0.5f)
        //处理布局的边界问题
        if (searchNewTopMargin < searchMinTopMargin) {
            searchNewTopMargin = searchMinTopMargin
        }
        if (searchNewWidth < searchMinWidth) {
            searchNewWidth = searchMinWidth
        }

        var alpha1: Float = (255 * alphaNewHeight / alphaMaxHeight)
        if (alpha1 < 0)
            alpha1 = 0f
        tvHomeLocal.setTextColor(
            Color.argb(255, alpha1.toInt(), alpha1.toInt(), alpha1.toInt())
        )

        var alpha2: Float =
            255 * (alphaMaxHeight - alphaNewHeight) / alphaMaxHeight
        if (alpha2 > 255)
            alpha2 = 255f
        clHomeSearch.setBackgroundColor(
            Color.argb(alpha2.toInt(), 255, 255, 255)
        )
        BarUtils.setStatusBarColor(
            requireActivity(), Color.argb(alpha2.toInt(), 255, 255, 255)
        )
        BarUtils.setStatusBarLightMode(
            requireActivity(), alpha2 > 180
        )
        alphaStatus = alpha2.toInt()

        flHomeSearch.layoutParams =
            (flHomeSearch.layoutParams as ViewGroup.MarginLayoutParams).apply {
                topMargin = searchNewTopMargin.toInt()
                width = searchNewWidth.toInt()
            }
    }

}